<template>
  <div class="app-container">
    <el-row :gutter="15">
      <el-col>
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">生成配置：项目:{{ project }},表:{{ tableName }},workspace:{{ workspace }}/{{ form.projectRoot }}</span>
            <el-button :loading="configLoading" icon="el-icon-check" size="mini" class="fr" type="primary" @click="doSubmit">保存</el-button>
            <el-button :loading="configLoading" icon="el-icon-arrow-down" size="mini" class="fr" style="margin-right: 12px" @click="showHide()">展开</el-button>
          </div>
          <el-form v-show="configShow" ref="form" :model="form" :rules="rules" size="small" label-width="100px">
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="作者名称" prop="author">
                  <el-input v-model="form.author" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="模块名称" prop="moduleName">
                  <el-input v-model="form.moduleName" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <span class="tips">模块的名称，请选择项目中已存在的模块</span>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="至于包下" prop="pack">
                  <el-input v-model="form.pack" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <span class="tips">项目包的名称，生成的代码放到哪个包里面</span>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="功能描述" prop="apiAlias">
                  <el-input v-model="form.apiAlias" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <span class="tips">领域模型的中文名称，用于接口文档中</span>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="前端路径" prop="path">
                  <el-input v-model="form.path" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <span class="tips">输入views文件夹下的目录，不存在即创建</span>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="去表前缀" prop="prefix">
                  <el-input v-model="form.prefix" placeholder="默认不去除表前缀" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <span class="tips">默认不去除表前缀，可自定义</span>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="是否覆盖" prop="cover">
                  <el-radio-group v-model="form.cover" size="mini">
                    <el-radio-button label="true">是</el-radio-button>
                    <el-radio-button label="false">否</el-radio-button>
                  </el-radio-group>
                  <span class="tips">谨防误操作，请慎重选择</span>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="模板类型" prop="catatype">
                  <el-radio-group v-model="form.catatype" size="mini">
                    <el-radio-button label="Mybatis" checked="true">mybatis模板</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item label="生成UI组件" prop="genUi">
                  <el-radio-group v-model="form.genUi" size="mini">
                    <el-radio-button label="true">是</el-radio-button>
                    <el-radio-button label="false">否</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="UI类型" prop="genType">
                  <el-radio-group v-model="form.genType" size="mini">
                    <el-radio-button label="i18n">国际化版本</el-radio-button>
                    <el-radio-button label="zh">中文版本</el-radio-button>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>

      <el-col style="margin-bottom: 10px; height: 98%">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">字段配置：{{ tableName }}</span>
            <el-button :loading="genLoading" icon="el-icon-s-promotion" size="mini" style="float: right; padding: 6px 9px" type="success" @click="toGen">保存&生成</el-button>
            <el-button :loading="columnLoading" icon="el-icon-check" size="mini" style="float: right; padding: 6px 9px; margin-right: 9px" type="primary" @click="saveColumnConfig">保存</el-button>
            <el-button size="mini" style="margin-right: 2px; float: right" type="primary">
              <router-link :to="'/generator/preview?project=' + project + '&tableName=' + tableName"> 预览</router-link>
            </el-button>

            <el-tooltip class="item" effect="dark" content="数据库中表字段变动时使用该功能" placement="top-start">
              <el-button :loading="syncLoading" icon="el-icon-refresh" size="mini" style="float: right; padding: 6px 9px" type="info" @click="sync">同步</el-button>
            </el-tooltip>
          </div>
          <el-form size="small" label-width="90px">
            <el-table v-loading="loading" :data="data" :max-height="tableHeight" size="small" style="width: 100%; height: 90%; margin-bottom: 5px">
              <el-table-column prop="columnName" label="字段名称" width="120" />
              <el-table-column prop="columnType" label="字段类型" width="70" />
              <el-table-column prop="remark" label="字段描述">
                <template slot-scope="scope">
                  <el-input v-model="data[scope.$index].remark" size="mini" class="edit-input" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="必填" width="50px">
                <template slot-scope="scope">
                  <el-checkbox v-model="data[scope.$index].notNull" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="列表" width="50px">
                <template slot-scope="scope">
                  <el-checkbox v-model="data[scope.$index].listShow" />
                </template>
              </el-table-column>
              <el-table-column align="center" label="表单" width="50px">
                <template slot-scope="scope">
                  <el-checkbox v-model="data[scope.$index].formShow" />
                </template>
              </el-table-column>
              <el-table-column label="表单类型" width="120">
                <template slot-scope="scope">
                  <el-select v-model="data[scope.$index].formType" filterable class="edit-input" clearable size="mini" placeholder="请选择">
                    <el-option label="文本框" value="Input" />
                    <el-option label="文本域" value="Textarea" />
                    <el-option label="单选框" value="Radio" />
                    <el-option label="下拉框" value="Select" />
                    <el-option label="日期框" value="Date" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="查询方式" width="100">
                <template slot-scope="scope">
                  <el-select v-model="data[scope.$index].queryType" filterable class="edit-input" clearable size="mini" placeholder="请选择">
                    <el-option label="=" value="=" />
                    <el-option label="Like" value="Like" />
                    <el-option label="In" value="In" />
                    <el-option label="!=" value="!=" />
                    <el-option label=">=" value=">=" />
                    <el-option label="<=" value="<=" />
                    <el-option label="NotNull" value="NotNull" />
                    <el-option label="BetWeen" value="BetWeen" />
                  </el-select>
                </template>
              </el-table-column>
              <!--<el-table-column label="日期注解">
                <template slot-scope="scope">
                  <el-select v-model="data[scope.$index].dateAnnotation"
                             filterable class="edit-input" clearable size="mini" placeholder="请选择">
                    <el-option label="自动创建时间" value="CreationTimestamp" />
                    <el-option label="自动更新时间" value="UpdateTimestamp" />
                  </el-select>
                </template>
              </el-table-column>-->
              <el-table-column label="关联字典">
                <template slot-scope="scope">
                  <el-select v-model="data[scope.$index].dictName" filterable class="edit-input" clearable size="mini" placeholder="请选择">
                    <el-option v-for="item in dicts" :key="item.id" :label="item.text + ':' + item.id" :value="item.id" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="子表" width="260px;" style="horiz-align: center">
                <template slot-scope="scope">
                  <div style="width: 100%; position: relative">
                    <el-select v-model="data[scope.$index].subEntity" style="width: 49%" filterable class="edit-input" clearable size="mini" placeholder="请选择子表" @change="selectSubEntity">
                      <el-option v-for="item in crud.data" :key="item.tableName" :label="item.remark + ' : ' + item.tableName" :value="item.tableName" />
                    </el-select>
                    <el-select v-model="data[scope.$index].subEntityField" style="width: 49%" filterable class="edit-input" :disabled="data[scope.$index].subEntity == null" clearable size="mini" placeholder="请选择子表字段">
                      <el-option v-for="item in tableFields" :key="item.columnName" :label="item.remark === '' ? item.columnName : item.remark + ' : ' + item.columnName" :value="item.columnName" />
                    </el-select>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import crud from '@/mixins/crud'
import { update, getTableGenConfig, generatorColumns } from '@/api/generator/genConfig'
import { save, sync, generator } from '@/api/generator/generator'
import { getDictCodes } from '@/api/dict-data'
import CRUD, { presenter, header } from '@crud/crud'
export default {
  name: 'GeneratorConfig',
  components: {},
  mixins: [crud, presenter(), header()],
  cruds() {
    return CRUD({ url: '/business/api/generator/tables', params: { size: 50, pageSize: 50 }})
  },
  data() {
    return {
      configShow: false,
      workspace: '',
      activeName: 'first',
      tableName: '',
      tableHeight: 850,
      columnLoading: false,
      configLoading: false,
      dicts: [],
      tables: [],
      tableFields: [],
      syncLoading: false,
      genLoading: false,
      form: { id: null, project: '', projectRoot: '', tableName: '', author: '', pack: '', path: '', moduleName: '', cover: 'false', apiPath: '', prefix: '', apiAlias: null, genUi: 'true', genType: 'i18n', catatype: 'Mybatis' },
      rules: {
        author: [{ required: true, message: '作者不能为空', trigger: 'blur' }],
        pack: [{ required: true, message: '包路径不能为空', trigger: 'blur' }],
        moduleName: [{ required: true, message: '包路径不能为空', trigger: 'blur' }],
        path: [{ required: true, message: '前端路径不能为空', trigger: 'blur' }],
        apiAlias: [{ required: true, message: '接口名称不能为空', trigger: 'blur' }],
        cover: [{ required: true, message: '不能为空', trigger: 'blur' }],
        genUi: [{ required: true, message: '是否生成UI组件不能为空', trigger: 'blur' }],
        genType: [{ required: true, message: 'UI类型不能为空', trigger: 'blur' }],
        catatype: [{ required: true, message: '模板类型不能为空', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.tableHeight = document.documentElement.clientHeight - 320
    this.tableName = this.$route.query.tableName
    this.project = this.$route.query.project
    this.$nextTick(() => {
      this.init()
      getTableGenConfig(this.project, this.tableName).then((data) => {
        this.form = data
        this.form.project = this.project
        this.workspace = data.workspace
        this.form.cover = this.form.cover.toString()
      })
      getDictCodes(this.project).then((data) => {
        this.dicts = data.data
      })
    })
  },
  methods: {
    beforeInit() {
      this.url = '/business/api/generator/columns'
      const tableName = this.tableName
      this.params = { tableName }
      return true
    },
    saveColumnConfig() {
      this.columnLoading = true
      this.data.map((item) => {
        item.listShow = item.listShow || false
        item.formShow = item.formShow || false
      })
      save(this.data)
        .then((res) => {
          this.notify('保存成功', 'success')
          this.columnLoading = false
        })
        .catch((err) => {
          this.columnLoading = false
        })
    },
    selectSubEntity(val) {
      // tableFields 子表字段
      generatorColumns({ pageNumber: 1, pageSize: 100, tableName: val }).then((res) => {
        if (res.totalElements > 0) {
          this.tableFields = res.content
        }
      })
    },
    showHide() {
      this.configShow = !this.configShow
    },
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.configLoading = true
          this.form.project = this.project
          update(this.form)
            .then((res) => {
              this.notify('保存成功', 'success')
              this.form = res
              this.form.cover = this.form.cover.toString()
              this.configLoading = false
              this.showHide()
            })
            .catch((err) => {
              this.configLoading = false
              console.log(err.response.data.message)
            })
        }
      })
    },
    sync() {
      this.syncLoading = true
      sync([this.tableName])
        .then(() => {
          this.init()
          this.notify('同步成功', 'success')
          this.syncLoading = false
        })
        .then(() => {
          this.syncLoading = false
        })
    },
    toGen() {
      this.genLoading = true
      save(this.data)
        .then((res) => {
          this.notify('配置保存成功', 'success')
          // 生成代码
          generator(this.project, this.tableName, 0)
            .then((data) => {
              this.genLoading = false
              this.notify('代码生成成功', 'success')
            })
            .catch((err) => {
              this.genLoading = false
              console.log(err.response.data.message)
            })
        })
        .catch((err) => {
          this.genLoading = false
          console.log(err.response.data.message)
        })
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss">
.edit-input {
  .el-input__inner {
    border: 1px solid #e5e6e7;
  }
}
.tips {
  font-size: 12px;
  color: #afafaf;
}
/deep/ .input-with-select .el-input-group__prepend {
  background-color: #fff;
}
/deep/ .el-card__header {
  padding: 2px 2px !important;
}
/deep/ .el-card__body {
  padding: 5px !important;
}
/deep/ el-form-item--small .el-form-item__label {
  width: 52px;
}
</style>
